/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Graph.java
 *
 * Created on 14 Φεβ 2011, 11:28:45 πμ
 */
package panels.charts;

import components.MyDraggable;
import exceptions.ErrorMessages;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Paint;
import java.awt.image.BufferedImage;
import java.awt.image.ImageFilter;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import models.Statistics;
import models.Statistics.KindStats;
import models.Statistics.MonthlyStats;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.ui.TextAnchor;
import org.jopendocument.panel.Messages;
import org.jopendocument.util.PrintUtilities;
import receipts.Main;
import tools.Helper;
import tools.options.Options;

/**
 *
 * @author ssoldatos
 */
public class Graph extends MyDraggable {

  private static final long serialVersionUID = 45675756786L;
  private String[] names;
  private Vector<Object> collection;
  private int type;
  public static int MAX_RESULTS = 100;
  private int page = 0;
  private int totalPages;
  private ChartPanel cpanel;
  private int PIE = 0;
  private int BARS = 1;
  private int chartType = 0;
  private JFreeChart pieChart;
  private JFreeChart barsChart;

  /** Creates new form Graph */
  public Graph() {
  }

  public Graph(String[] names, Vector<Object> collection, int type) {
    this.names = names;
    this.collection = collection;
    this.type = type;
    Main.glassPane.activate(null);
    initComponents();
    addCharts();
    setLocationRelativeTo(null);
    setVisible(true);
    
  }

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    panel = new javax.swing.JPanel();
    bt_close = new javax.swing.JButton();
    cb_sort = new javax.swing.JCheckBox();
    tabs = new javax.swing.JTabbedPane();
    piechartPanel = new javax.swing.JPanel();
    barschartPanel = new javax.swing.JPanel();
    bt_save = new javax.swing.JButton();
    bt_print = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

    panel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

    bt_close.setForeground(new java.awt.Color(204, 204, 204));
    bt_close.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/exit.png"))); // NOI18N
    bt_close.setToolTipText("Κλείσιμο γραφήματος");
    bt_close.setBorder(null);
    bt_close.setBorderPainted(false);
    bt_close.setContentAreaFilled(false);
    bt_close.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
    bt_close.setFocusPainted(false);
    bt_close.setIconTextGap(1);
    bt_close.setRequestFocusEnabled(false);
    bt_close.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        bt_closeActionPerformed(evt);
      }
    });

    cb_sort.setText("Ταξινόμιση ανά ποσό");
    cb_sort.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        cb_sortActionPerformed(evt);
      }
    });

    piechartPanel.setMinimumSize(new java.awt.Dimension(600, 400));

    javax.swing.GroupLayout piechartPanelLayout = new javax.swing.GroupLayout(piechartPanel);
    piechartPanel.setLayout(piechartPanelLayout);
    piechartPanelLayout.setHorizontalGroup(
      piechartPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGap(0, 783, Short.MAX_VALUE)
    );
    piechartPanelLayout.setVerticalGroup(
      piechartPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGap(0, 442, Short.MAX_VALUE)
    );

    tabs.addTab("Γράφημα πίτας", new javax.swing.ImageIcon(getClass().getResource("/images/pie_chart.png")), piechartPanel); // NOI18N

    javax.swing.GroupLayout barschartPanelLayout = new javax.swing.GroupLayout(barschartPanel);
    barschartPanel.setLayout(barschartPanelLayout);
    barschartPanelLayout.setHorizontalGroup(
      barschartPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGap(0, 783, Short.MAX_VALUE)
    );
    barschartPanelLayout.setVerticalGroup(
      barschartPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGap(0, 442, Short.MAX_VALUE)
    );

    tabs.addTab("Γράφημα μπάρας", new javax.swing.ImageIcon(getClass().getResource("/images/chart.png")), barschartPanel); // NOI18N

    bt_save.setForeground(new java.awt.Color(204, 204, 204));
    bt_save.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.png"))); // NOI18N
    bt_save.setToolTipText("Αποθήκευση του γραφήματος ως εικόνα");
    bt_save.setBorder(null);
    bt_save.setBorderPainted(false);
    bt_save.setContentAreaFilled(false);
    bt_save.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
    bt_save.setFocusPainted(false);
    bt_save.setIconTextGap(1);
    bt_save.setRequestFocusEnabled(false);
    bt_save.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        bt_saveActionPerformed(evt);
      }
    });

    bt_print.setForeground(new java.awt.Color(204, 204, 204));
    bt_print.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/printer.png"))); // NOI18N
    bt_print.setToolTipText("Εκτύπωση του γραφήματος");
    bt_print.setBorder(null);
    bt_print.setBorderPainted(false);
    bt_print.setContentAreaFilled(false);
    bt_print.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
    bt_print.setFocusPainted(false);
    bt_print.setIconTextGap(1);
    bt_print.setRequestFocusEnabled(false);
    bt_print.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        bt_printActionPerformed(evt);
      }
    });

    jLabel1.setFont(jLabel1.getFont().deriveFont(jLabel1.getFont().getStyle() | java.awt.Font.BOLD, jLabel1.getFont().getSize()+2));
    jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel1.setText("Στατιστικά Γραφήματα");

    javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
    panel.setLayout(panelLayout);
    panelLayout.setHorizontalGroup(
      panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(panelLayout.createSequentialGroup()
        .addContainerGap()
        .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelLayout.createSequentialGroup()
            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 686, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(bt_print, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(bt_save, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(bt_close, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelLayout.createSequentialGroup()
            .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
              .addComponent(tabs, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 788, Short.MAX_VALUE)
              .addComponent(cb_sort))
            .addContainerGap())))
    );
    panelLayout.setVerticalGroup(
      panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(panelLayout.createSequentialGroup()
        .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(bt_close, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(bt_save, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(bt_print, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addGroup(panelLayout.createSequentialGroup()
            .addGap(11, 11, 11)
            .addComponent(jLabel1)))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(cb_sort)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(tabs, javax.swing.GroupLayout.DEFAULT_SIZE, 478, Short.MAX_VALUE)
        .addContainerGap())
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void bt_closeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_closeActionPerformed
    Main.glassPane.deactivate();
    dispose();
  }//GEN-LAST:event_bt_closeActionPerformed

  private void cb_sortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_sortActionPerformed
    addCharts();
  }//GEN-LAST:event_cb_sortActionPerformed

  private void bt_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_saveActionPerformed
    int i = tabs.getSelectedIndex();
    BufferedImage image = null;
    if (i == PIE) {
      image = pieChart.createBufferedImage(600, 400);
    } else if (i == BARS) {
      image = barsChart.createBufferedImage(600, 400);
    }
    JFileChooser jfc = new JFileChooser(Options.USER_DIR);
    jfc.setFileFilter(new ImageFileFilter());
    jfc.showSaveDialog(this);
    if (jfc.getSelectedFile() != null) {
      File file = jfc.getSelectedFile();
      if(file.exists()){
        int an = Helper.confirm("Αποθήκευση γραφήματος", "Το αρχείο "+ file.getName() + " υπάρχει ήδη.\n"
            + "Θέλετε να το επαναγράψετε;" );
        if(an == JOptionPane.NO_OPTION){
          return;
        }
      }
      String[] t = file.getName().split("\\.");
      String ext = t[t.length - 1];
      if (Helper.isInArray(ext, ImageFileFilter.EXTENSIONS)) {
        saveImage(image, file, ext);
      } else {
        Helper.message(ErrorMessages.NOT_IMAGE_FILE, "Αποθήκευση γραφήματος", JOptionPane.ERROR_MESSAGE);
        Main.log(Level.SEVERE, ErrorMessages.NOT_IMAGE_FILE, null);

      }
    }



  }//GEN-LAST:event_bt_saveActionPerformed

  private void bt_printActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_printActionPerformed
    Component comp = tabs.getSelectedComponent();
    comp.setSize(comp.getWidth()/2, comp.getHeight()/2);
    PrintUtilities.printComponent(comp);
  }//GEN-LAST:event_bt_printActionPerformed

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JPanel barschartPanel;
  private javax.swing.JButton bt_close;
  private javax.swing.JButton bt_print;
  private javax.swing.JButton bt_save;
  private javax.swing.JCheckBox cb_sort;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JPanel panel;
  private javax.swing.JPanel piechartPanel;
  private javax.swing.JTabbedPane tabs;
  // End of variables declaration//GEN-END:variables

  private void addCharts() {
    piechartPanel.removeAll();
    piechartPanel.validate();
    piechartPanel.repaint();

    barschartPanel.removeAll();
    barschartPanel.validate();
    barschartPanel.repaint();
    if (cpanel != null) {
      cpanel = null;
    }
    pieChart = new PieChart(collection, 0, type, cb_sort.isSelected()).chart;
    barsChart = new BarsChart(collection, 0, type, cb_sort.isSelected()).chart;
    cpanel = new ChartPanel(pieChart);
    cpanel.setSize(piechartPanel.getSize());
    piechartPanel.add(cpanel);
    piechartPanel.getParent().validate();
    cpanel = new ChartPanel(barsChart);
    cpanel.setSize(barschartPanel.getSize());
    barschartPanel.add(cpanel);
    barschartPanel.getParent().validate();
  }

  private void saveImage(BufferedImage image, File file, String ext) {
    BufferedImage bimg;
    if (ext.equals("png") || ext.equals("gif")) {
      bimg = new BufferedImage(600, 400, BufferedImage.TYPE_INT_ARGB);
    } else {
      bimg = new BufferedImage(600, 400, BufferedImage.TYPE_INT_RGB);
    }
    bimg.getGraphics().drawImage(image, 0, 0, this);
    try {
      ImageIO.write(bimg, ext, file);
      Helper.message("Το γράφημα αποθηκεύθηκε", "Αποθήκευση γραφήματος", JOptionPane.INFORMATION_MESSAGE);
    } catch (IOException ex) {
      Helper.message(ErrorMessages.GRAPH_SAVE, "Αποθήκευση γραφήματος", JOptionPane.ERROR_MESSAGE);
      Main.log(Level.SEVERE, ErrorMessages.GRAPH_SAVE, ex);
    }
  }
}
